import java.beans.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class AccountsProper extends javax.swing.JFrame {

    /** Creates new form AccountsProper */
    public AccountsProper() {
        initComponents();
       getDatabase();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Employees and Accounts Module");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Employee Number", "Last Name", "First Name", "Username", "Status"
            }
        ));
        jTable1.setToolTipText("");
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setResizable(false);

        jButton1.setText("Add Employee");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton4.setText("Back");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton2.setText("Edit Employee");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton5.setText("Enable/Disable Employee");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addGap(11, 11, 11)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 250, Short.MAX_VALUE)
                .addComponent(jButton4)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
          SaveEmployee AddEmployee = new SaveEmployee();
        AddEmployee.setType(0);
        AddEmployee.show();
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Object x = jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        SaveEmployee EditEmployee = new SaveEmployee();
        int i = Integer.parseInt((String)x);
        EditEmployee.setIndex(i);
        EditEmployee.setType(1);
        EditEmployee.show();
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        MainMenu x = new MainMenu();
        x.show();
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
  Object x = jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        Object xp = jTable1.getValueAt(jTable1.getSelectedRow(), 4);
        int i = Integer.parseInt((String)x);
        if(xp == "enabled")
        {
            JDialog dbox = new JDialog();
    dbox.setSize(400,250);
    int response = JOptionPane.showConfirmDialog(
                    dbox, "Are you sure you want to disable this employee?", " ", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (response == JOptionPane.YES_OPTION ) {
        disableData(i);
        JOptionPane.showMessageDialog(null, "Disable Successful!!", "Disable",JOptionPane.WARNING_MESSAGE);
        AccountsProper y = new AccountsProper();
        y.show();
              dbox.dispose();
        this.dispose();
        }
           else if (response == JOptionPane.NO_OPTION ) {
                dbox.dispose();
            }
        }      
       else{
               JDialog dbox1 = new JDialog();
    dbox1.setSize(400,250);
    int response1 = JOptionPane.showConfirmDialog(
                    dbox1, "Are you sure you want to enable this employee?", " ", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (response1 == JOptionPane.YES_OPTION ) {
       enableData(i);
       JOptionPane.showMessageDialog(null, "Enable Successful!!", "Enable",JOptionPane.WARNING_MESSAGE);
        AccountsProper y = new AccountsProper();
        y.show();
           dbox1.dispose();
        this.dispose();
            }
             else if (response1 == JOptionPane.NO_OPTION ) {
                dbox1.dispose();
            }
           }      
        this.dispose();    }//GEN-LAST:event_jButton5ActionPerformed

    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AccountsProper().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

   DB DB = new DB();
   int rowCount = 0;

   Connection conn;
   PreparedStatement pstmt;
   Statement stmt;
   ResultSet rset;
   String query;

   	public void getDatabase(){

            Vector row = new Vector();
            rowCount = 0;

            try {
                       DB.connect();
                       conn = DB.getConn();

                       query = "select employee.employeeNo, employee.surname, employee.firstname, account.username, employee.status from employee, account where employee.employeeNo = account.employeeNo order by employee.employeeNo;";
                       pstmt = conn.prepareStatement(query);
                       rset = pstmt.executeQuery();


                       while(rset.next())
                       {
                             row.addElement(rset.getString("employeeNo"));
                             row.addElement(rset.getString("surname"));
                             row.addElement(rset.getString("firstname"));
                             row.addElement(rset.getString("username")); 
                            int x = rset.getInt("status");
                             if(x == 0){
                                 row.addElement("disabled");
                             }
                             else {
                                 row.addElement("enabled");
                             }
                             
                             rowCount++;  
                       }
                       setValues(row, rowCount);
                    DB.disconnect();
                    pstmt.close();

             } catch (Exception ex) {
                   JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
             }

       }

       public void setValues(Vector row, int rowCount){
            Object z[] = {null,null,null,null};
            DefaultTableModel model = (javax.swing.table.DefaultTableModel)jTable1.getModel();
            jTable1.setModel(model);

            if(rowCount > 22){
                int q = rowCount - 22;
                for(int w = 0; w < q; w++){
                    model.addRow(z);
                }
            }
           
       		int columnNum = 0;
       		for(int i = 1; i <= rowCount; i++){
			for(columnNum = 0; columnNum < 5; columnNum++){
       		jTable1.setValueAt(row.elementAt(columnNum+(5*(i-1))), i-1, columnNum);}
       		columnNum = 0;}
       }

      public void disableData(int i)
      {
            try {

            		DB.connect();
            		conn = DB.getConn();
                        
                      query = "update employee set status = 0 where employeeNo = '"+i+"';";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                   DB.disconnect();
                   pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }

            getDatabase();
      }
       public void enableData(int i)
      {
            try {

            		DB.connect();
            		conn = DB.getConn();
                        
                      query = "update employee set status = 1 where employeeNo = '"+i+"';";

                      pstmt = conn.prepareStatement(query);

                      pstmt.executeUpdate();

                   DB.disconnect();
                   pstmt.close();


            } catch (Exception ex) {
            		  JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }

            getDatabase();
      }
}

